import { BASE_URL } from "../../utils/config";

interface Course {
  id: number;
  courseName: string;
  icon: string;
  color: string;
  checkType: number;
  faceImage: string;
}

Page({
  data: {
    showCamera: false,
    isClockIn: false,
    courserId: ''
  },

  onLoad(options: any) {
    // 获取课程数据
    this.setData({
      courserId: options.courseId
    });
  },

  // 显示相机
  handleShowCamera() {
    this.setData({ showCamera: true });
  },

  // 拍照
  async takePhoto() {
    const camera = wx.createCameraContext();
    camera.takePhoto({
      quality: 'high',
      success: async (res) => {
        // TODO: 调用后端API上传人脸照片
        console.log('拍照成功：', res.tempImagePath);
        await this.uploadFacePhoto(res.tempImagePath);
      },
      fail: (err) => {
        console.error('拍照失败：', err);
        wx.showToast({
          title: '拍照失败',
          icon: 'error'
        });
      }
    });
  },

  // 上传人脸照片
  async uploadFacePhoto(tempFilePath: string) {
    // TODO: 实现上传人脸照片到后端的逻辑
    const fileResult = await new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${BASE_URL}/file/upload`,
        filePath: tempFilePath,
        name: 'file',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail: reject
      });
    });
    // 修改用户信息
    const token = wx.getStorageSync('token');
    console.log("fileResult: ", fileResult);
    const { data } = JSON.parse(fileResult);
    wx.request({
      url: `${BASE_URL}/face/verify`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: {
        faceImage: data.url,
        courseId: this.data.courserId
      },
      success: (res) => {
        const data = res.data as any;
        console.log("upload res data", data);
        if(data.code !== 200) {
          wx.showToast({
            title: data.msg || '打卡失败',
            icon: 'error'
          });
          return;
        } else {
          wx.showToast({
            title: '打卡成功',
            icon:'success'
          });

          this.setData({
            showCamera: false,
            isClockIn: true
          });

          setTimeout(() => {
            // 返回上一页
            wx.switchTab({
              url: '/pages/index/index'
            })
          }, 1000);
        }
      }
    })
  },

  // 取消拍照
  cancelPhoto() {
    this.setData({ showCamera: false });
  },

  // 相机错误处理
  error(e: any) {
    console.error('相机错误：', e.detail);
    wx.showToast({
      title: '相机启动失败',
      icon: 'error'
    });
  }
});